function MainAppCtrl($scope,Rest,eventBroadcast) {
    /**
     *get the currentUser
     */
    $scope.currentCardHolder = Rest.getCurrentCardHolder();
    $scope.visualdata = Rest.getVisulizationData();

    $scope.currentPage = {home : "current", profile: "", visual: ""};



    $scope.selectPage = function(page) {
        if(page == "visual") {
            $scope.currentPage.visual = "current";
            $scope.currentPage.home = "";
            $scope.currentPage.profile = "";
        } else if(page == "home") {
            $scope.currentPage.visual = "";
            $scope.currentPage.home = "current";
            $scope.currentPage.profile = "";
        } else if(page == "profile") {
            $scope.currentPage.visual = "";
            $scope.currentPage.home = "";
            $scope.currentPage.profile = "current";
        }
    }

    /**
     * Authenticate
     */
    $scope.authenticate = function() {
        //authenticate and assign the current User
        //non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
        $scope.currentCardHolder = Rest.authenticate({},$scope.currentCardHolder, function(data){

           if(data.authenticated) {
               eventBroadcast.broadcast('handleAuthenticate');
               eventBroadcast.broadcast('handleVisualData');
           }



        });

    }

    $scope.$on('handleVisualData', function(event,args) {
        $scope.visualdata = Rest.getVisulizationData();
    });


    $scope.logout = function() {
        $scope.currentCardHolder = Rest.logout(function(data) {
            eventBroadcast.broadcast('handleAuthenticate');;
        });
    }

}


function MyProfileCtrl($scope,Rest,eventBroadcast) {

    $scope.monthlyBudgetLeft = Rest.getVisulizationData();
    $scope.fund = {};
    $scope.visualdata = Rest.getVisulizationData();
    $scope.addFund = function() {
        Rest.addFundToCurrentCardHolder({},$scope.fund,function() {
            $scope.visualdata = Rest.getVisulizationData();
            eventBroadcast.broadcast('handleVisualData');
        });
    }



    $scope.$on('handleAuthenticate', function(event,args) {
        $scope.visualdata = Rest.getVisulizationData();
    });



}


function VisualCtrl($scope,Rest) {



    $scope.visualdata = Rest.getVisulizationData();



    $scope.$on('handleAuthenticate', function() {


        Rest.getVisulizationData(function(data){
            $scope.visualdata = data;

        });
    });

}


function CafeDetailCtrl(Rest, $routeParams, $location, $scope,eventBroadcast) {
    
    $scope.cafe = Rest.getCafeById({id1: $routeParams.cafeid});
    $scope.cafemenus = Rest.getCafeMenusByCafeId({id1: $routeParams.cafeid});
    $scope.visualdata = Rest.getVisulizationData();

    $scope.currentPage.review = "";
    $scope.currentPage.order = "current";


    $scope.userreview = {rating: 3}
    $scope.reviews = Rest.getReviewsByCafeId({id1: $routeParams.cafeid},function(data) {

        for(var i = 0; i < data.reviews.length; i++ ) {
            var review = data.reviews[i];
            if(i%2 == 1) {
                review.oddItem = "_odditem";
            }
        }
        $scope.reviews = data;

        });



    $scope.transaction = {};
    $scope.transaction.total = 0;
    $scope.transaction.paymentType = {address_state : "CA"};
    $scope.transaction.deliveryType = {address_state : "CA"};

    $scope.currentCardHolder = Rest.getCurrentCardHolder();
    $scope.state = 'order';


    $scope.startOrder = function () {
        $scope.state = 'order';
        $scope.currentPage.review = "";
        $scope.currentPage.order = "order";


    }


    $scope.$on('handleAuthenticate', function() {
        Rest.getCurrentCardHolder(function(data){
            $scope.currentCardHolder = data;
            if($scope.currentCardHolder.authenticated) {
                $scope.transaction.paymentType.payment = "accessCard";
            } else {
                $scope.transaction.paymentType.payment = "creditCard";
            }
        })


    });

    $scope.completeOrder = function() {
        
        if($scope.transaction.deliveryType.delivery == "delivery") {
            if($scope.transaction.deliveryType.name == null || $scope.transaction.deliveryType.name.length == 0 ) {
                alert("Error: Please enter your name");
                return;
            }
            else if(transaction.deliveryType.order_phone == null || transaction.deliveryType.order_phone.length == 0) {
                alert("Error: Please enter your phone number");
            }

            else if($scope.transaction.deliveryType.address_street == null || $scope.transaction.deliveryType.address_street.length == 0) {
                alert("Error: Please enter your street");
                return;
            } else if($scope.transaction.deliveryType.address_city  == null || $scope.transaction.deliveryType.address_city.length == 0) {
                alert("Error: Please enter your city");
                return;
            } else if($scope.transaction.deliveryType.zip == null || $scope.transaction.deliveryType.address_city.length == 0) {
                alert("Error: Please enter your zip");
                return;
            }
        }
        if($scope.transaction.paymentType.payment == "creditCard") {
           if($scope.transaction.paymentType.address_street == null || $scope.transaction.paymentType.address_street.length == 0) {
                alert("Error: Please enter Billing address");
                return;
            } else if($scope.transaction.paymentType.address_street == null || $scope.transaction.paymentType.address_street.length == 0) {
                alert("Error: Please enter Billing zip");
                return;
            } else if($scope.transaction.paymentType.creditNum == null || $scope.transaction.paymentType.creditNum.length == 0) {
                alert("Error: Please enter  Credit Card Number");
                return;
            } else if($scope.transaction.paymentType.creditExpDate == null || $scope.transaction.paymentType.creditExpDate.length == 0) {
                alert("Error: Please enter  Credit Card Expiration date");
                return;
            } else if($scope.transaction.paymentType.credit_csv == null || $scope.transaction.paymentType.creditExpDate.length == 0) {
                alert("Error: Please enter  Credit CSV");
                return;
            }
        }
        
        







        if($scope.visualdata.monthly_left_amount <   $scope.transaction.total) {
            alert("Order Cannot Complete: InSufficent Fund");
            return;
        }
        if($scope.currentCardHolder.authenticated) {







            Rest.addCardHolderTracker({},{total_purchase_amount: $scope.transaction.total},function() {
                $scope.state = 'completedorder';
                if($scope.transaction.deliveryType.delivery == "pickup") {
                    $scope.transaction.completeMessage = "Your order will be ready to pick up in 15 minutes";
                } else {
                    $scope.transaction.completeMessage = "Your order will be deliver in 20 minutes";
                }
                eventBroadcast.broadcast('handleVisualData');
            });

        } else {
            if($scope.transaction.deliveryType.delivery == "pickup") {
                $scope.transaction.completeMessage = "Your order will be ready to pick up in 15 minutes";
            } else {
                $scope.transaction.completeMessage = "Your order will be deliver in 20 minutes";
            }
            $scope.state = 'completedorder';
        }





    }





    $scope.startSummary = function() {




        if($scope.transaction.deliveryType.delivery == null) {
            $scope.transaction.deliveryType.delivery = "pickup";
        }
        if($scope.transaction.paymentType.orderType == null) {
            if($scope.currentCardHolder.authenticated) {
                $scope.transaction.paymentType.payment = "accessCard";
            } else {
                $scope.transaction.paymentType.payment = "creditCard";
            }

        }

        calculateOrder();
        if($scope.transaction.total == 0) {
            alert("Please select an Item");
            return;
        };
        $scope.state = 'summary';

    }


    calculateOrder = function() {


        var total = 0;
        var orders = [];
        var cafemenus = $scope.cafemenus.cafemenus;
        var orderCount = 1;
        for(var i = 0; i < cafemenus.length; i++ ) {
            var cafemenuArray = cafemenus[i];
            for(var j = 0; j < cafemenuArray.length; j++) {
                var cafemenu = cafemenuArray[j];
                var order = {};
                if(cafemenu.quantity != null) {
                    order.quantity  = cafemenu.quantity;
                    order.total = cafemenu.quantity * cafemenu.price;
                    order.name = cafemenu.name;
                    if((orderCount%2) == 1) {
                        order.oddItem = "oddItem";
                    }
                    orders.push(order);
                    total+= order.total;

                    orderCount++;
                }
            }


        }

        if("delivery" == $scope.transaction.deliveryType.delivery) {
            var delivery = {};
            delivery.total = 15.00
            delivery.quantity  = "-";
            delivery.name = "Delivery";
            orders.push(delivery);
            total+=delivery.total;
            if((orderCount) %2 == 1) {
                delivery.oddItem = "oddItem";
                orderCount++;
            }
        }


        if("accessCard" == $scope.transaction.paymentType.payment) {
            var discount = {}
            discount.total = total*-.10;
            discount.quantity = "-";
            total+=discount.total;
            orders.push(discount);
            discount.name = "10% Access Card Discount";
            if((orderCount) %2 == 1) {
                discount.oddItem = "oddItem";
                orderCount++;
            }
        }


        $scope.transaction.orders = orders;
        $scope.transaction.total = total;



    }

    $scope.startReview = function () {
        $scope.state = 'review';

        $scope.currentPage.review = "current";
        $scope.currentPage.order = "";
    }




    $scope.$watch('transaction.deliveryType.delivery', function(newval, oldval){
        if($scope.state == "summary") {
            calculateOrder();

        }

    }, true);


    $scope.$watch('transaction.paymentType.payment', function(newval, oldval){
        if($scope.state == "summary") {
            calculateOrder();

        }

    }, true);



    $scope.reset = function() {

        for(var i = 0; i <  $scope.cafemenus.cafemenus.length; i++) {
            $scope.cafemenus.cafemenus[i].quantity = 0;
            $scope.cafemenus.cafemenus[i].selected = true;
        }



    }


    $scope.addUserReview = function() {

        if($scope.userreview.comment == null) {
            alert("Please enter comment");
            return;
        }
        Rest.addUserReview({cafe: $routeParams.cafeid, rating: $scope.userreview.rating, comment: $scope.userreview.comment},function(data) {
            Rest.getReviewsByCafeId({id1: $routeParams.cafeid},function(data) {

                for(var i = 0; i < data.reviews.length; i++ ) {
                    var review = data.reviews[i];
                    if(i%2 == 1) {
                        review.oddItem = "_odditem";
                    }
                }
                $scope.reviews = data;

            });


        });




    }








}
